package benchmark.clients;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import org.apache.log4j.Logger;


import soapclient.Interval;
import soapclient.MeterReadings;
import soapclient.MeterReadingsService;
import soapclient.Reading;

import benchmark.Client;

public class SoapClient implements Client {	
	private static Logger soaplogger = Logger.getLogger("soaplogger");
	private MeterReadingsService port;
	
	public SoapClient(){
		String host = "localhost";
		String serviceport = "8080";
		
		if(System.getenv().containsKey("READINGS_HOST")){
			host = System.getenv().get("READINGS_HOST");
		}
		
		if(System.getenv().containsKey("READINGS_PORT")){
			serviceport = System.getenv().get("READINGS_PORT");
		}
		
		String baseUri = "http://" + host + ":" + serviceport + "/";
				
		try {
			Service service = Service.create(new URL(
					baseUri + "MeterReadings?wsdl"), 
					new QName("http://meterreadingservie", "MeterReadingsServiceImplService"));
			port = service.getPort(MeterReadingsService.class);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
					
	}

	static private long numReadings = 0;
    static private String interval = "MINUTE";
    static
    {
    	if(System.getenv().containsKey("READINGS_NUMREADINGS")){
			numReadings = Long.parseLong(System.getenv().get("READINGS_NUMREADINGS"));
		}
    	if(System.getenv().containsKey("READINGS_INTERVAL")){
			interval = System.getenv().get("READINGS_INTERVAL");
		}
    }
    
	public void sendRequest() {
		MeterReadings readings = null;
		long tFrom=(int)(Math.random()*(java.lang.System.currentTimeMillis()/1000));
		long start=System.currentTimeMillis();
		if(port != null)			
			readings = port.getMeterReadings((int)(Math.random() * 10000), tFrom ,numReadings, Interval.valueOf(interval));
		long end = System.currentTimeMillis();
		soaplogger.info("" + (end - start));
		/*for(Reading r : readings.getReadings())
		{
			System.out.print(r.getDate());
			System.out.print(r.getPower());
			System.out.print(' ');
		}
		System.out.println();*/
	}

}
